// graphMixin.js
import * as echarts from 'echarts';
import { ref, onUnmounted } from 'vue';

export const graphMixin = {
    setup() {
        const graphChart = ref(null);
        const graphData = ref({ nodes: [], relationships: [] });
        const graphContainer = ref(null);
        const isFullscreen = ref(false);
        const loading = ref(false);

        const renderGraph = () => {
            if (!graphContainer.value) return;

            if (graphChart.value) {
                graphChart.value.dispose();
            }

            graphChart.value = echarts.init(graphContainer.value);
            const nodes = graphData.value.nodes || [];
            const links = graphData.value.relationships || [];

            if (nodes.length === 0) return;

            const processedNodes = nodes.map(node => ({
                ...node,
                symbolSize: 25,
                itemStyle: {
                    color: node.isHighTech ? '#67C23A' : '#409EFF'
                },
                label: {
                    fontSize: 12,
                    distance: 5,
                    show: true,
                    position: 'right',
                    formatter: function(params) {
                        return params.data.name.length > 10 ?
                            params.data.name.substring(0, 10) + '...' :
                            params.data.name;
                    }
                }
            }));

            const processedLinks = links.map(link => ({
                ...link,
                value: link.value || '',
                lineStyle: {
                    color: '#999',
                    curveness: 0.1
                }
            }));

            const option = {
                title: {
                    text: '企业关系图谱',
                    top: 'top',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        if (params.dataType === 'node') {
                            return `
                <div style="font-weight:bold;margin-bottom:5px;">${params.data.name}</div>
                <div>员工数量: ${params.data.value?.employeeCount || '未知'}</div>
                <div>企业规模: ${params.data.value?.companyScale || '未知'}</div>
                <div>注册资本: ${params.data.value?.registeredCapital || '未知'}万元</div>
                <div>成立年份: ${params.data.value?.establishYear || '未知'}</div>
                <div>所在省份: ${params.data.value?.province || '未知'}</div>
                <div>风险数量: ${params.data.value?.riskCount || '未知'}</div>
                <div>是否高新: ${(params.data.value?.isHighTech || params.data.isHighTech) ? '是' : '否'}</div>
              `;
                        } else {
                            const sourceNode = nodes.find(n => n.id === params.data.source);
                            const targetNode = nodes.find(n => n.id === params.data.target);
                            return `
                <div style="font-weight:bold;margin-bottom:5px;">关系类型: ${params.data.type || '供应关系'}</div>
                <div>${sourceNode?.name || params.data.source} → ${targetNode?.name || params.data.target}</div>
              `;
                        }
                    }
                },
                legend: {
                    data: ['高新技术企业', '普通企业'],
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    name: '企业关系',
                    type: 'graph',
                    layout: 'force',
                    data: processedNodes,
                    links: processedLinks,
                    categories: [
                        { name: '高新技术企业' },
                        { name: '普通企业' }
                    ],
                    roam: true,
                    draggable: true,
                    label: {
                        fontSize: 12,
                        distance: 5,
                        position: 'right',
                        show: true,
                        formatter: '{b}'
                    },
                    emphasis: {
                        focus: 'adjacency',
                        lineStyle: {
                            width: 4
                        }
                    },
                    force: {
                        gravity: 0.1,
                        friction: 0.6,
                        repulsion: 150,
                        edgeLength: 80
                    }
                }]
            };

            graphChart.value.setOption(option, true);
        };

        const toggleFullscreen = () => {
            const graphCard = document.querySelector('.graph-card');
            if (!isFullscreen.value) {
                if (graphCard.requestFullscreen) {
                    graphCard.requestFullscreen();
                } else if (graphCard.mozRequestFullScreen) {
                    graphCard.mozRequestFullScreen();
                } else if (graphCard.webkitRequestFullscreen) {
                    graphCard.webkitRequestFullscreen();
                } else if (graphCard.msRequestFullscreen) {
                    graphCard.msRequestFullscreen();
                }
                isFullscreen.value = true;
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
                isFullscreen.value = false;
            }

            setTimeout(() => {
                if (graphChart.value) {
                    graphChart.value.resize();
                }
            }, 300);
        };

        onUnmounted(() => {
            if (graphChart.value) {
                graphChart.value.dispose();
            }
        });

        return { graphChart, graphData, graphContainer, isFullscreen, loading, renderGraph, toggleFullscreen };
    }
};